package com.study.daily.algozuo.y2021.m10.day1021;

import java.util.HashMap;

/**
 * @descriptions:
 * @author: Tom
 * @date: 2021/10/21 上午 11:57
 * @version: 1.0
 */
public class Code01_KM {
    // 请保证arr中，只有一种数出现了K次，其他数都出现了M次
    // 請找到出現K次的數, M > K
    public static int km(int[] arr, int m ,int k) {
        if(map.size() == 0){
            mapCreate(map);
        }
        int[] count = new int[32];
        int ans = 0;
        int rightestOne = 0;
        for(int num: arr){
            while(num != 0){
                rightestOne = num &(-num);
                count[map.get(rightestOne)]++;
                num ^= rightestOne;
            }
        }
        for (int i = 0; i < 32; i++) {

            if(count[i]% m != 0){
                if(count[i] % m == k){
                    ans |= (1<< i);
                }else{
                    return -1;
                }
            }
        }
        if(ans == 0){
            int zeroCount = 0;
            for(int num: arr){
                if(num == 0) zeroCount++;
            }
            if(zeroCount %m != k){
                return -1;
            }
        }
        return ans;
    }

    public static HashMap<Integer, Integer> map = new HashMap<>();
    public static HashMap<Integer, Integer> mapCreate(HashMap<Integer, Integer> map) {
        int value = 1;
        for(int i = 0; i < 32; i++){
            map.put(value, i);
            value <<= 1;
        }
        return map;
    }
}
